<template>
  <el-loading
    v-if="visible"
    :background="background"
    :custom-class="customClass"
    :element="element"
    :body="body"
    :fullscreen="fullscreen"
    :lock="lock"
    :spinner="spinner"
    :text="text"
  />
</template>
<script setup lang="ts">
import { ElLoading } from 'element-plus'
import type { LoadingOptions } from './types'

const props = withDefaults(defineProps<LoadingOptions>(), {
  text: '加载中...',
  background: 'rgba(255, 255, 255, 0.9)',
  spinner: 'el-icon-loading',
  fullscreen: false,
  lock: true,
  customClass: '',
  body: false,
  visible: false,
})

// 创建加载实例
const loadingInstance = ElLoading.service({
  text: props.text,
  background: props.background,
  spinner: props.spinner,
  fullscreen: props.fullscreen,
  lock: props.lock,
  customClass: props.customClass,
  element: props.element,
  body: props.body,
})

// 监听可见性变化
watch(
  () => props.visible,
  (val) => {
    if (val) {
      loadingInstance.close()
    } else {
      loadingInstance.close()
    }
  }
)

// 组件卸载时关闭加载
onUnmounted(() => {
  loadingInstance.close()
})
</script>
